package com.example.security.controller;

import com.example.security.common.ResultInfo;
import com.example.security.entity.RoleEntity;
import com.example.security.service.RoleService;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 角色
 *
 * @author novel
 * @date 2020/11/4
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    private final RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    @GetMapping
    public ResultInfo list() {
        List<RoleEntity> list = roleService.list();
        return ResultInfo.success("success", list);
    }


    /**
     * 新增或编辑
     */
    @PostMapping("/save")
    public RoleEntity save(RoleEntity role) {
        return roleService.save(role);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public Object delete(int id) {
        Optional<RoleEntity> role = roleService.findById(id);
        if (role.isPresent()) {
            roleService.deleteById(id);
            return ResultInfo.success("删除成功", 200);
        } else {
            return ResultInfo.error(500, "没有找到该对象");
        }
    }

    /**
     * 查询
     */
    @PostMapping("/find")
    public Object find(int id) {
        Optional<RoleEntity> role = roleService.findById(id);
        return role.map(roleEntity -> ResultInfo.success("success", roleEntity)).orElseGet(() -> ResultInfo.error(404, "没有找到该对象"));
    }

    /**
     * 分页查询
     */
    @PostMapping("/list")
    public Page<RoleEntity> list(RoleEntity role,
                                 @RequestParam(required = false, defaultValue = "0") int pageNumber,
                                 @RequestParam(required = false, defaultValue = "10") int pageSize) {

        //创建匹配器，需要查询条件请修改此处代码
        ExampleMatcher matcher = ExampleMatcher.matchingAll();

        //创建实例
        Example<RoleEntity> example = Example.of(role, matcher);
        //分页构造
        Pageable pageable = PageRequest.of(pageNumber, pageSize);

        return roleService.findAll(example, pageable);
    }
}
